#ifndef HTTPCLIENT_H
#define HTTPCLIENT_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QUrl>
#include <QDebug>
#include <QEventLoop>
#include <QTimer>
#include <QFile>
#include <QDateTime>
#include <type_traits>
#include <memory>
#include <functional>



class HttpClientBase:public QObject
{
    Q_OBJECT
public:
    explicit HttpClientBase(QObject* parent = nullptr);
    virtual ~HttpClientBase() = default;
    void LinkStart();

protected:
    QNetworkAccessManager* m_manager;
    QMap<QByteArray, QByteArray> m_headers;
};



template<typename TRequest,typename TResponse>
class HttpClient: public HttpClientBase
{
public:
    explicit HttpClient(QObject* parent = nullptr): HttpClientBase(parent) {}

    std::shared_ptr<TResponse> postSync(const QString& url,const TRequest& requset,int timeoutMs = 30000)
    {
        auto response = std::make_shared<TResponse>();

        // 1. 设置请求数据
        QJsonObject jsonData = requset.toJson();
        qDebug() << "Sending POST request to:" << url;

        // 2. 创建网络请求
        QNetworkRequest request;
        request.setUrl(QUrl(url));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

        // 可以添加其他请求头，如认证信息
        // request.setRawHeader("Authorization", "Bearer your_token");

        // 3. 发送请求
        QJsonDocument doc(jsonData);
        QByteArray postData = doc.toJson();
        QNetworkReply* reply = m_manager->post(request, postData);

        // 4. 等待请求完成（同步方式）
        QEventLoop loop;
        connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);

        // 设置超时
        QTimer timer;
        timer.setSingleShot(true);
        connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
        timer.start(timeoutMs);

        loop.exec();

        // 5. 处理响应
        if (timer.isActive()) {
            // 请求正常完成
            timer.stop();

            if (reply->error() != QNetworkReply::NoError) {
                // 处理网络错误
                // response->errorMessage = reply->errorString();
                qWarning() << "Network error:" << reply->errorString();
            } else {
                // 获取响应数据
                QByteArray rawResponse = reply->readAll();
                // response->rawResponse = rawResponse;

                // 解析JSON响应
                QJsonDocument jsonDoc = QJsonDocument::fromJson(rawResponse);

                if (!jsonDoc.isNull() && jsonDoc.isObject()) {
                    response->fromJson(jsonDoc.object());
                } else {
                    // response->errorMessage = "Invalid JSON response";
                    qWarning() << "Invalid JSON response:" << rawResponse;
                }
            }
        } else {
            // 请求超时
            disconnect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
            reply->abort();
            // response->errorMessage = "Request timeout";
            qWarning() << "Request timeout";
        }

        reply->deleteLater();
        return response;
    }
    void postAsync(const QString& url,const TRequest& requestData,std::function<void(std::shared_ptr<TResponse>)> callback)

    {
        // 1. 设置请求数据
        QJsonObject jsonData = requestData.toJson();
        qDebug() << "Sending async POST request to:" << url;

        // 2. 创建网络请求
        QNetworkRequest request;
        request.setUrl(QUrl(url));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

        // 3. 发送请求
        QJsonDocument doc(jsonData);
        QByteArray postData = doc.toJson();
        QNetworkReply* reply = m_manager->post(request, postData);

        // 4. 连接完成信号
        connect(reply, &QNetworkReply::finished, [this, reply, callback]() {
            auto response = std::make_shared<TResponse>();

            if (reply->error() != QNetworkReply::NoError) {
                // 处理网络错误
                response->errorMessage = reply->errorString();
                qWarning() << "Network error:" << reply->errorString();
            } else {
                // 获取响应数据
                QByteArray rawResponse = reply->readAll();
                response->rawResponse = rawResponse;

                // 解析JSON响应
                QJsonDocument jsonDoc = QJsonDocument::fromJson(rawResponse);

                if (!jsonDoc.isNull() && jsonDoc.isObject()) {
                    response->fromJson(jsonDoc.object());
                } else {
                    response->errorMessage = "Invalid JSON response";
                    qWarning() << "Invalid JSON response:" << rawResponse;
                }
            }

            // 调用回调函数
            if (callback) {
                callback(response);
            }

            reply->deleteLater();
        });
    }


};

#endif // HTTPCLIENT_H
